package com.ronri.ams.sample;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.model.LatLng;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.ronri.ams.SystemEnvironmental;
import com.ronri.ams.bean.entList;
import com.ronri.common.UrlEncode;
import com.ronri.common.WaitDialog;
import com.ronri.db.RemoteDataService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cz.nongyetongv5.application.InitApplication.gSampleInfo;


/**
 * 文件：ams.java
 * 包名：com.ronri.ams.sample;   --- 正式发布时需要修正
 * 说明：轮播组件
 * 作者：MS During
 * 日期：2017/5/10
 * 历史：
 */
public class activity_control_map_select extends abstract_activity {

    private String _TAG = "activity_control_map_select";

    private Context mContext = null;

    private TextView mbtnFind = null;
    private TextView mbtnList = null;
    private TextView mbtnAdd = null;

    private EditText mEditKey = null;
    private List<MapItem> mItems = new ArrayList<>();

    private int mSelect = 0;
    private fragmentMap fMap = null;
    private fragmentList fList = null;

    // 模块管理
    private FragmentManager fragmentManager;
    MapStatus ms;
    LinearLayout layout;


    /// 显示内容
    private class MapAdapter extends PagerAdapter {

        // 界面列表
        private List<View> views;
        private Activity activity;


        public MapAdapter(List<View> views, Activity activity) {
            this.views = views;
            this.activity = activity;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(views.get(position), 0);
            return views.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(views.get(position));
        }

        // 获得当前界面数
        @Override
        public int getCount() {
            if (views != null) {
                return views.size();
            }
            return 0;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    /****
     * 初始化Fragment
     */
    private void ShowFragment(int i) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        // 设置动画效果
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

        if (fMap != null) {
            fragmentTransaction.hide(fMap);
        }

        if (fList != null) {

            fragmentTransaction.hide(fList);
        }

        if (i == 0) {
            if (fMap == null) {
                fMap = new fragmentMap();
                fMap.setIRemoteMapData(new IRemoteMapData() {
                    @Override
                    public void GetPageData(int nPage) {
                        getRemotePageData(nPage, "");
                    }

                    @Override
                    public void GetRemoteData(double lng, double lat) {
                        //                        getRemoteData(lng, lat);
                        //                        getRemotePageData(1);
                    }

                    @Override
                    public void Seleced(MapItem item) {
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();

                        bundle.putInt("id", item.mId);
                        bundle.putString("title", item.mTtitle);
                        intent.putExtras(bundle);

                        setResult(RESULT_OK, intent);
                        finish();
                    }

                    @Override
                    public List<MapItem> GetItemList() {
                        return null;
                    }
                });

                fragmentTransaction.add(R.id.content, fMap);

            } else {
                fragmentTransaction.show(fMap);
            }
        }

        if (i == 1) {
            if (fList == null) {
                fList = new fragmentList();
                fList.setSearchKey(mEditKey.getText().toString());
                fList.setIRemoteMapData(new IRemoteMapData() {
                    @Override
                    public void GetPageData(int nPage) {
                        getRemotePageData(nPage, "");
                    }

                    @Override
                    public void GetRemoteData(double lng, double lat) {
                        getRemoteData(0, 0);
                    }

                    @Override
                    public void Seleced(MapItem item) {
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();

                        bundle.putInt("id", item.mId);
                        bundle.putString("title", item.mTtitle);
                        intent.putExtras(bundle);

                        setResult(RESULT_OK, intent);
                        finish();
                    }

                    @Override
                    public List<MapItem> GetItemList() {
                        return mItems;
                    }
                });

                fragmentTransaction.add(R.id.content, fList);
            } else {
                fragmentTransaction.show(fList);

            }
        }

        fragmentTransaction.commit();
    }

    /****
     * 创建视图
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contorl_map_select);
        Log.i("aaa", "activity_control_map_select");
        mContext = this;

        // 设置标题
        setTitle("受检对象", "常规检索");

        // 初始化
        init();

        mbtnFind = (TextView) findViewById(R.id.btnSearch);
        mbtnList = (TextView) findViewById(R.id.btn_locate_list);
        mbtnAdd = (TextView) findViewById(R.id.btn_add_entity);
        mEditKey = (EditText) findViewById(R.id.btnFind);

        mbtnFind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 已当前点获取周边数据
                //                getRemoteData(0, 0);
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive() && getCurrentFocus() != null) {
                    if (getCurrentFocus().getWindowToken() != null) {
                        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }

                if (mSelect == 0) {
                    mbtnList.setText("地图");
                    ShowFragment(1);
                    mSelect = 1;
                }
                getRemotePageData(1, mEditKey.getText().toString());
            }
        });

        mEditKey.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Drawable drawable = mEditKey.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null)
                    return false;
                //如果不是按下事件，不再处理
                if (event.getAction() != MotionEvent.ACTION_UP)
                    return false;
                if (event.getX() > mEditKey.getWidth()
                        - mEditKey.getPaddingRight()
                        - drawable.getIntrinsicWidth()) {
                    mEditKey.setText("");
                }
                return false;
            }
        });

        mEditKey.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelect == 0) {
                    mbtnList.setText("地图");
                    ShowFragment(1);
                    mSelect = 1;
                }
            }
        });

        mbtnList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //                if (mItems.size() <= 0)
                //                    return;

                if (mSelect == 0) {
                    mbtnList.setText("地图");
                    ShowFragment(1);
                    mSelect = 1;
                } else {
                    mbtnList.setText("列表");
                    ShowFragment(0);
                    mSelect = 0;
                }
            }
        });

        //新增受检对象
        mbtnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(activity_control_map_select.this, AddEntityActivity.class), 14000);
            }
        });
        fragmentManager = getSupportFragmentManager();

        // 默认显示地图
        ShowFragment(0);

        // 已当前点获取周边数据
        getRemoteData(0, 0);
    }


    @Override
    public boolean CancelReturn() {
        return super.CancelReturn();
    }

    @Override
    public boolean SureReturn() {
        Intent intent = new Intent(mContext, activity_map_search.class);
        startActivityForResult(intent, 13000);
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 13000:
                case 14000:
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();

                    bundle.putInt("id", data.getExtras().getInt("id"));
                    bundle.putString("title", data.getExtras().getString("name"));
                    intent.putExtras(bundle);

                    setResult(RESULT_OK, intent);
                    finish();
                    break;
            }
        }
    }

    /***
     * 获取数据
     * @param pageindex
     */
    public void getRemotePageData(int pageindex, String key) {
        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
        String szRemoteAddress = "http://120.55.93.238:8080/ams/api/entList.json";

        //        String szRemoteAddress ="http://192.168.0.77:8080/ams/api/entList.json";

        Log.i("test", "szRemoteAddress-->" + szRemoteAddress);
        Map<String, Object> mParam = new HashMap<String, Object>();

        String szEnt = mEditKey.getText().toString();

        try {
            mParam.put("addFrom", 1);
            mParam.put("addMark", "android");
            mParam.put("page", pageindex);
            mParam.put("pageSize", 10);
            mParam.put("region_code", gSampleInfo.getSample_area());
            mParam.put("ent_name", key);

        } catch (Exception ex) {

        }

        fList.mPageIndex = pageindex;
        fList.setSearchKey(mEditKey.getText().toString());

        Log.i("test", "mParam-->" + mParam.toString());
        // 获取远程数据
        remoteDataService.getRemoteData(szRemoteAddress,
                UrlEncode.getUrlParamsByMap(mParam, false),
                InitApplication.SystemConfig.getModule().getTdetail().getMethod(),
                new RemoteDataService.OnRemoteDataEvent() {
                    // 返回结果
                    @Override
                    public void OnResultEvent(String szString) {
                        Log.i("test", "szString-->" + szString);
                        if (szString.isEmpty())
                            return;

                        try {
                            entList entBean = JSON.parseObject(szString, entList.class);

                            if (entBean.isSuccess()) {
                                int total = entBean.getData().getTotal();
                                mItems = new ArrayList<MapItem>();

                                for (entList.DataBean.RowsBean iTem : entBean.getData().getRows()) {
                                    // 添加Marker点
                                    LatLng locate = new LatLng(iTem.getLatitude(), iTem.getLongitude());

                                    MapItem myitem = new MapItem(locate);

                                    myitem.mTtitle = iTem.getName();
                                    myitem.mHumen = iTem.getCharge();
                                    myitem.mRegionCode = iTem.getRegion();
                                    myitem.mTelphone = iTem.getTel();
                                    myitem.mAddress = iTem.getAddress();
                                    myitem.mId = iTem.getId();

                                    mItems.add(myitem);
                                }

                                if (fList != null) {
                                    if (mSelect == 1) {
                                        fList.RefreshData(mItems);
                                        fList.mTotalPages = total;
                                    }
                                }

                                if (fMap != null) {
                                    if (mSelect == 0)
                                        fMap.CreateCluster(mItems);
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }

                    // 状态控制，是否显示加载过程
                    @Override
                    public void OnRuningState(int nStatus) {
                        if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
                            WaitDialog.ShowDialog(activity_control_map_select.this, "请稍后...");
                        } else {
                            WaitDialog.HideDialog();
                        }
                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                }
        );
    }

    /****
     * 获取远程数据
     */
    public void getRemoteData(double lng, double lat) {
        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
        String szRemoteAddress = InitApplication.SystemConfig.getBase().RemoteAddress(
                InitApplication.SystemConfig.getModule().getEntlist().getAddress());

        Map<String, Object> mParam = new HashMap<String, Object>();

        String szEnt = mEditKey.getText().toString();

        try {
            mParam.put("addFrom", 1);
            mParam.put("addMark", "android");
            mParam.put("page", 1);
            mParam.put("pageSize", 20);
            mParam.put("region_code", gSampleInfo.getSample_area());
            mParam.put("ent_name", szEnt);
            mParam.put("range", 5);
            mParam.put("longitude", lng);
            mParam.put("latitude", lat);

        } catch (Exception ex) {

        }

        // 获取远程数据
        remoteDataService.getRemoteData(szRemoteAddress,
                UrlEncode.getUrlParamsByMap(mParam, false),
                InitApplication.SystemConfig.getModule().getTdetail().getMethod(),
                new RemoteDataService.OnRemoteDataEvent() {
                    // 返回结果
                    @Override
                    public void OnResultEvent(String szString) {
                        if (szString.isEmpty())
                            return;

                        try {
                            entList entBean = JSON.parseObject(szString, entList.class);

                            if (entBean.isSuccess()) {
                                int total = entBean.getData().getTotal();
                                mItems = new ArrayList<MapItem>();

                                for (entList.DataBean.RowsBean iTem : entBean.getData().getRows()) {
                                    // 添加Marker点
                                    LatLng locate = new LatLng(iTem.getLatitude(), iTem.getLongitude());

                                    MapItem myitem = new MapItem(locate);

                                    myitem.mTtitle = iTem.getName();
                                    myitem.mHumen = iTem.getCharge();
                                    myitem.mRegionCode = iTem.getRegion();
                                    myitem.mTelphone = iTem.getTel();
                                    myitem.mAddress = iTem.getAddress();
                                    myitem.mId = iTem.getId();

                                    mItems.add(myitem);
                                }

                                if (fList != null) {
                                    if (mSelect == 1) {
                                        fList.RefreshData(mItems);
                                        fList.mTotalPages = total;
                                    }
                                }

                                if (fMap != null) {
                                    if (mSelect == 0) {
                                        fMap.CreateCluster(mItems);
                                    }
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }

                    // 状态控制，是否显示加载过程
                    @Override
                    public void OnRuningState(int nStatus) {
                        if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
                            WaitDialog.ShowDialog(activity_control_map_select.this, "请稍后...");
                        } else {
                            WaitDialog.HideDialog();
                        }
                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                }
        );
    }


    /**
     * 封装定位结果和时间的实体类
     *
     * @author baidu
     */
    class LocationEntity {
        BDLocation location;
        long time;
    }
}
